package com.baide.sanguanheyi.ct;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@ChannelHandler.Sharable
public class ConnectorIdleStateTrigger  extends ChannelInboundHandlerAdapter {
    @Autowired
    XmlUtils xmlUtils;

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent)evt).state();
            if (state == IdleState.WRITER_IDLE) {
                ctx.writeAndFlush(Unpooled.unreleasableBuffer(Unpooled.copiedBuffer(xmlUtils.getHeartContent(), CharsetUtil.UTF_8)).duplicate());
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}